<template>
  <el-cascader
    :options="options"
    :props="defaultProps"
    :show-all-levels="false"
    clearable
  />
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, ref } from 'vue'
import { IDepartment } from '@/http/types/department'
import { getDepartments } from '@/http/department'
import { toTree, treeConvertToArr } from '@/utils'
import _ from 'lodash'
// import _ from 'lodash'
const props = defineProps({
  multiple: {
    type: Boolean,
    default: false,
  },
  // 单选才有效
  checkChild: {
    type: Boolean,
    default: true,
  },
  currentId: {
    type: String,
    default: '',
  },
})

const defaultProps = computed(() => ({
  checkStrictly: true,
  value: 'id',
  label: 'displayName',
  multiple: props.multiple,
  emitPath: false,
}))
const options = ref<({ disabled?: boolean } & IDepartment)[]>([])
onMounted(async () => {
  await nextTick()
  loadOption()
})
const loadOption = async () => {
  const res = await getDepartments()
  const data = res.items
  // 为数据增加 disabled 属性
  if (!props.multiple && !props.checkChild) {
    if (props.currentId) {
      // needDisables = []
      const arr = treeConvertToArr(_.cloneDeep(data))
      const ids = getNeedDisIds(arr, props.currentId)
      arr.forEach((item) => {
        item.disabled = ids.includes(item.id)
      })
      options.value = toTree(arr)
    } else {
      options.value = data
    }
  } else {
    options.value = data
  }
}
// 等待处理成disable的数据
const getNeedDisIds = (arr: any, id: string) => {
  let needDisables: any = [id]
  const mapTree = (itemId: any) => {
    const ids = arr
      .filter((item: any) => item.parentId === itemId)
      .map((e: any) => e.id)
    needDisables = needDisables.concat(ids)
    ids.forEach((e: any) => {
      mapTree(e)
    })
  }
  mapTree(id)
  return needDisables
}
</script>

<style lang="scss" scoped></style>
